package com.lyf.core.util;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.lyf.core.compant.Perm;
import com.lyf.core.pojo.Menu;
import com.lyf.core.pojo.Role;
import com.lyf.core.pojo.User;
import com.lyf.core.service.MenuService;
import com.lyf.core.service.RoleService;
import com.lyf.core.service.UserService;
 
public class  Shrio extends AuthorizingRealm{  
	  
	private static final String OR_OPERATOR = " or ";  
	private static final String AND_OPERATOR = " and ";  
	private static final String NOT_OPERATOR = "not ";  
	
	@Autowired
    private UserService userService;  
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private RoleService roleService;
    /** 
     * 权限认证，获取登录用户的权限
     */  
    @Override  
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {  
        String user_id = (String) principalCollection.fromRealm(getName()).iterator().next();  
        //此处连库匹配了登录用户的数据，具体怎么做，需要根据个人需求而定
        User user=userService.findByUserId(user_id);  
        
        if(user!=null){  
        	
        	List<Role> list = roleService.findUserRoles(user_id);
        	
        	SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();  
        	Set<String> roles = new HashSet<>();
        	Set<String> pers = new HashSet<>();
        	
        	//如果是superadmin 直接抽取所有的菜单权限列表
        	if(user_id.equals(UserService.SUPER_ADMIN_ID)) {
        		Map<String, Perm> ms = CommonUtils.getAllUrlPerms();
            	for(Entry<String, Perm> e: ms.entrySet()) {
            		String url = e.getKey();
            		if(url == null ||url.trim().equals("")) continue;
            		if(url.startsWith("./")){
            			url = url.substring(1);
            		}
            		if(!url.startsWith("/")){
            			url = "/" + url ;
            		}
            	 
            		pers.add(url);
            		pers.add(e.getKey());
            	}
        	} else {
        		List<Menu> menus = menuService.findByUser(user_id, true, false);
            	 
                 
                 for(Menu m : menus) {
                 	pers.add(m.getMenu_id());
                 	String url = m.getMenu_url();
                 	if(url == null ||url.trim().equals("")) continue;
                 	
                 	if(url.startsWith("./")){
                 		url = url.substring(1);
                 	} 
                 
                 	pers.add(url);
                 	
                 
                 }
        		
        	}
        	 
             //获取用户的角色名称
             
            for(Role r : list) {
            	roles.add(r.getRole_name());
            	 
            }
            
           
        	System.out.println("pers : " + pers);
            info.setRoles(roles);  
            info.setStringPermissions(pers);
            //获取用户的权限
            
            
            
//            List<Role> roleList= user.getRoleList();  
//            for (Role role : roleList) {  
//                info.addStringPermissions(role.getPermissionsName());  
//            }  
            return info;  
        }  
        return null;  
    }  
  
     
    
    /** 
     * 登录认证，创建用户的登录信息
     */  
    @Override  
    protected AuthenticationInfo doGetAuthenticationInfo(  
            AuthenticationToken authenticationToken) throws AuthenticationException {  
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;  
        //判断用户登录状态
        User user=userService.findByUserId(token.getUsername());  
        if(user!=null){  
            //保存用户登录信息到认证中 
            return new SimpleAuthenticationInfo(user.getUser_id(), user.getUser_pass(), getName());  
        }  
        return null;  
    }  
    
 
    
    @Override
    public boolean isPermitted(PrincipalCollection principals, String permission) {
    	if(permission.contains(OR_OPERATOR)) {  
            String[] permissions = permission.split(OR_OPERATOR);  
            for(String orPermission : permissions) {  
                if(isPermittedWithNotOperator(principals, orPermission)) {  
                    return true;  
                }  
            }  
            return false;  
        } else if(permission.contains(AND_OPERATOR)) {  
            String[] permissions = permission.split(AND_OPERATOR);  
            for(String orPermission : permissions) {  
                if(!isPermittedWithNotOperator(principals, orPermission)) {  
                    return false;  
                }  
            }  
            return true;  
        } else {  
            return isPermittedWithNotOperator(principals, permission);  
        }  
    }
    private boolean isPermittedWithNotOperator(PrincipalCollection principals, String permission) {  
        if(permission.startsWith(NOT_OPERATOR)) {  
            return !super.isPermitted(principals, permission.substring(NOT_OPERATOR.length()));  
        } else {  
            return super.isPermitted(principals, permission);  
        }  
    } 
}